
const app = getApp();
const { AskComponent } = app._require("common/index");
const { uploadFile } = app._require("utils/upload.file");
const authMixin = app._require("components/upload/src/image/auth.mixin.js").default;
let RecorderInstance = wx.getRecorderManager();
AskComponent({
    behaviors: [authMixin],
    properties: {
        action: {
            type: String,
            value: "",
        },
        url: {
            type: String,
            value: "",
        },
        props: {
            type: Object,
            value: {
                dir: "",
                suffix: "",
                limit: 10 * 1024 * 1024,
                timeout: 30 * 1000,
            },
            observer: "checkProps",
        },
    },
    data: {
        status: "PENDING",
    },
    methods: {
        setModel(e) {
            this.$emit("setModel", e);
        },
        changeRecord(){
            if(this.data.status === "PENDING"){
                this.startRecord();
            }else{
                this.endRecord();
            }
        },
        startRecord() {
            if (this.data.status !== "PENDING") {
                wx.askShowToastEx({
                    icon: "none",
                    title: "请先结束录音!",
                });
                return;
            }
            wx.showLoading({
                title: "启动中",
                mask: true,
            });
            const initRecord = () => {
                const options = {
                    duration: 10000,
                    sampleRate: 8000,
                    numberOfChannels: 2,
                    encodeBitRate: 48000,
                    format: "mp3",
                };
                RecorderInstance.start(options);
                RecorderInstance.onStart(() => {
                    this.setData({
                        status: "START",
                    });
                    wx.hideLoading();
                    wx.askShowToastEx({
                        icon: "none",
                        title: "录音开始!",
                    });
                });
                RecorderInstance.onError(e => {
                    wx.hideLoading();
                    this.setData({
                        status: "PENDING",
                    });
                });
                RecorderInstance.onPause(() => {
                    this.setData({
                        status: "PAUSE",
                    });
                });
                RecorderInstance.onStop(res => {
                    this.setData({
                        status: "STOP",
                    });
                    this.upload([res]);
                });
                RecorderInstance.onInterruptionBegin(() => {
                    this.endRecord();
                });
                RecorderInstance.onInterruptionEnd(() => {
                    this.endRecord();
                });
            };
            wx.getSetting({
                success:(sRes)=> {
                    console.log(sRes.authSetting);
                    if (!sRes.authSetting["scope.record"]) {
                        wx.authorize({
                            scope: "scope.record",
                            success: (aRes) => {
                                console.log("aRes", aRes);
                                initRecord();
                            },
                            fail: (aErr)=>{
                                wx.hideLoading();
                                wx.showModal({
                                    title: "温馨提示",
                                    content: "请先开启录音授权哦",
                                    success(res) {
                                        if (res.confirm) {
                                            wx.openSetting({
                                                success(oRes) {
                                                    if (!oRes.authSetting["scope.record"]) {
                                                        wx.askShowToastEx({
                                                            icon: "none",
                                                            title: "请开启录音授权!",
                                                        });
                                                    }
                                                }
                                            });
                                        } else if (res.cancel) {
                                            wx.askShowToastEx({
                                                icon: "none",
                                                title: "请开启录音授权!",
                                            });
                                        }
                                    },
                                });
                            }
                        });
                    }
                    if(sRes.authSetting["scope.record"]){
                        initRecord();
                    }
                },
            });
        },
        endRecord() {
            if (this.data.status === "PENDING") {
                wx.askShowToastEx({
                    icon: "none",
                    title: "请先开始录音!",
                });
                return;
            }
            RecorderInstance.stop();
        },
        async upload(files) {
            wx.showLoading({
                title: "上传中...",
                mask: true,
            });
            try {
                const nowTime = new Date();
                const uploadList = files.map(file => ({
                    dir: this.data.props.dir + nowTime.format("yyyy/MM/dd") + "/",
                    filePath: file.tempFilePath || "",
                    size: file.fileSize,
                    _id: "0choose",
                }));
                let url = "";
                console.log("getCredentials", this);
                const _response = await uploadFile(uploadList, {
                    limit: this.data.props.limit || 10 * 1024 * 1024,
                    timeout: this.data.props.timeout || 30 * 1000,
                    action: this.data.action,
                    initAuth: this.getCredentials.bind(this),
                    onReady: files => {
                        this.triggerEvent("update", {
                            type: "upload",
                            list: files,
                            item: null,
                        });
                    },
                    beforeUpload: (curFile, files) => {
                        this.triggerEvent("update", {
                            type: "upload",
                            list: files,
                            item: curFile,
                        });
                    },
                    afterUpload: (curFile, files, errors) => {
                        if (errors && errors.length > 0) {
                            wx.askShowToastEx({
                                icon: "none",
                                title: "上传文件只能在" + this.data.props.limit / 1024 / 1024 + "M以内",
                            });
                        }
                        url = curFile;
                        this.triggerEvent("update", {
                            type: "upload",
                            list: files,
                            item: curFile,
                        });
                    },
                });

                wx.hideLoading();
                console.log(url.src);
                this.$emit("setModel", { value: url.src });
                this.setData({
                    status: "PENDING",
                });
                this.triggerEvent("updateEnd", url);
            } catch (error) {
                wx.hideLoading();
                console.log(error);
            }
        },
    },
});
